﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.PlcModel;
using DeHeng_Mes.Model.PlcModel.door_01;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System.Linq;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using DeHeng_Mes.Model.OrderSingleton;
using MappingTable = DeHeng_Mes.Utils.MappingTable;
using System.Diagnostics;
using SqlSugar;
using System.Web.UI.WebControls;

namespace DeHeng_Mes.Dao
{
    public class OrderDao
    {

        #region

        #endregion

        /// <summary>
        /// 获取订单状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool GetOrderStatus(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>()
                      .Where(x => x.OrderId == orderId)
                      .Any();
            }
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<OrderStatus> GetOrder()
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>().ToList();
            }
        }


        /// <summary>
        /// 插入新订单信息
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        public int InsertOrder(OrderStatus orderStatus)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(orderStatus)
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 完成订单修改对应信息
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        public void UpdateOrder(string wo_code, string wo_status)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<OrderStatus>()
                  .SetColumns(x => x.EndTime == DateTime.Now)
                  .SetColumns(x => x.Status == wo_status)
                  .Where(x => x.OrderId == wo_code)
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 检查二维码数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public int CodeDataIsSave(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查找符合条件的记录
                int traceCode = db.Queryable<TraceCode>()
                                  .Where(x => x.TraceId == code)
                                  .Select(x => x.Id)
                                  .First();

                return traceCode;
            }
        }

        /// <summary>
        /// 存储二维码数据,并且返回主键
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public int CodeDataSave(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var traceCode = new TraceCode
                {
                    TraceId = code,
                };
                return db.Insertable(traceCode)
                       .ExecuteReturnIdentity();
            }
        }

        /// <summary>
        /// 检查焊接数据是否保存,保存则返回主键
        /// </summary>
        /// <param name="seamNo"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public int WeldDataIsSave(string seamNo, string startTime, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查找符合条件的记录
                int traceWeld = db.Queryable<TraceWeld>()
                                  .Where(x => x.SeamNo == seamNo && x.StartTime == startTime && x.Station == station)
                                  .Select(x => x.Id)
                                  .First();


                return traceWeld;
            }
        }

        /// <summary>
        /// 存储数据，并且返回主键
        /// </summary>
        /// <param name="traceWeld"></param>
        /// <returns></returns>
        public bool WeldDataSave(List<TraceWeld> weldDatas, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(weldDatas)
                         .AS($"trace_weld{HashUtils.GetHashAsInt(code, 10)}")
                         .ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 检查追溯码和工艺数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="weldIdsStr"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        public bool CodeAndOperationDataIsSave(int code, string weldIdsStr, string operation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<CodeOperationData>()
                         .Where(x => x.TraceId == code && x.OperationIds == weldIdsStr && x.Operation == operation)
                         .Any();
            }
        }

        /// <summary>
        /// 存储追溯码和工艺数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="weldIdsStr"></param>
        /// <param name="operation"></param>
        public void CodeAndOperationSave(int code, string weldIdsStr, string operation)
        {
            CodeOperationData codeOperationData = new CodeOperationData()
            {
                TraceId = code,
                OperationIds = weldIdsStr,
                Operation = operation
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(codeOperationData)
                  .ExecuteCommand();

                Tools.ProduceLogText($"存储了一条{operation}工艺与二维码的关联数据，二维码为{code}");
            }
        }

        /// <summary>
        /// 根据开始时间，结束时间查询是否存在数据，存在返回主键
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public int CNCDataIsSave(string startTime, string endTime)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查找符合条件的记录
                int traceCnc = db.Queryable<TraceCnc>()
                                  .Where(x => x.StartTime == startTime && x.EndTime == endTime)
                                  .Select(x => x.Id)
                                  .First();

                return traceCnc;
            }
        }

        /// <summary>
        /// 插入数据并且返回主键
        /// </summary>
        /// <param name="traceCnc"></param>
        /// <returns></returns>
        public bool CNCDataSave(List<TraceCnc> cncData, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(cncData).AS($"trace_cnc{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 根据编号、结果检查数据是否存在
        /// </summary>
        /// <param name="number"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public int CCDDataIsSave(string number, string result)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查找符合条件的记录
                int traceCCD = db.Queryable<TraceCCD>()
                                  .Where(x => x.Number == number && x.Result == result)
                                  .Select(x => x.Id)
                                  .First();

                // 如果没有找到记录，返回 null
                return traceCCD;
            }
        }

        /// <summary>
        /// 存储CCD数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool CCDDataSave(List<TraceCCD> traceCCDs, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(traceCCDs).AS($"trace_ccd{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 存储焊缝视觉数据
        /// </summary>
        /// <param name="traceWeldVision"></param>
        /// <returns></returns>
        public void WeldVisionDataSave(List<TraceWeldVision> traceWeldVision, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceWeldVision).AS($"trace_weld_vision{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand();
            }
        }

        /// <summary>
        /// 存储涂胶视觉数据
        /// </summary>
        /// <param name="traceGlueVision"></param>
        /// <returns></returns>
        public void GlueVisionDataSave(List<TraceGlueVision> traceGlueVision, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceGlueVision).AS($"trace_glue_vision{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand();
            }
        }

        /// <summary>
        /// 获取涂胶数据Id
        /// </summary>
        /// <param name="rageNo"></param>
        /// <param name="startTime"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public int GlueDataIsSave(string rageNo, string startTime, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查找符合条件的记录
                int traceGlueVision = db.Queryable<TraceGlue>()
                                  .Where(x => x.RangeNo == rageNo && x.StartTime == startTime && x.Station == station)
                                  .Select(x => x.Id)
                                  .First();

                // 如果没有找到记录，返回 null
                return traceGlueVision;
            }
        }

        /// <summary>
        /// 插入涂胶数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool GlueDataSave(List<TraceGlue> traceGlues, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(traceGlues).AS($"trace_glue{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 查找未结束的工单
        /// </summary>
        public List<OrderStatus> QueryOrder()
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>()
                         .Where(x => x.Status != "9")
                         .ToList();
            }
        }

        /// <summary>
        /// 查询未推送的数据
        /// </summary>
        /// <returns></returns>
        public List<OrderTrace> QueryOrderTrace()
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>().Where(x => x.Status1 == "0" || x.Status2 == "0").ToList();
            }
        }

        /// <summary>
        /// 根据主键查询OrderTrace数据
        /// </summary>
        /// <param name="id"></param>
        public static OrderTrace GetOrderTraceById(string id)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>().Where(x => x.Id == int.Parse(id)).First();
            }
        }

        /// <summary>
        /// 更新数据推送完成状态
        /// </summary>
        public void UpdatePushOkStatus(int id)
        {
            try
            {
                using (var db = SqlSugarConfig.Db)
                {
                    db.Updateable<OrderTrace>()
                        .SetColumns(x => x.Status1 == "1")
                        .Where(x => x.Id == id)
                        .ExecuteCommand();
                }
            }
            catch (Exception e)
            {
                Tools.ProduceLogTextError($"更新单件推送状态失败，原因是{e.Message}");
            }
        }

        /// <summary>
        /// 根据主键修改过站信息状态
        /// </summary>
        /// <param name="id"></param>
        public void UpDateStationStatus(int id, string traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(traceId, 10)}").SetColumns(x => x.IsSave == "1").Where(x => x.Id == id).ExecuteCommand();
            }
        }


        /// <summary>
        /// 判断拉铆数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pointCount"></param>
        /// <returns></returns>
        public bool RiveteDataIsSave(string code, string pointCount, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceRivete>()
                    .Where(x => x.TraceId == code && x.PointNo == pointCount && x.Station == station)
                    .AS($"trace_rivete{HashUtils.GetHashAsInt(code, 10)}")
                    .Any();
            }
        }

        /// <summary>
        /// 存储拉铆数据
        /// </summary>
        /// <param name="traceRivete"></param>
        public void SaveRiveteData(TraceRivete traceRivete)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceRivete)
                  .AS($"trace_rivete{HashUtils.GetHashAsInt(traceRivete.TraceId, 10)}")
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 查询压铆数据是否保存
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pointCount"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool ClinchDataIsSave(string code, string pointCount, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceRivete>()
                    .Where(x => x.TraceId == code && x.PointCount == pointCount && x.Station == station)
                    .AS($"trace_clinch{HashUtils.GetHashAsInt(code, 10)}")
                    .Any();
            }
        }

        /// <summary>
        /// 插入压铆数据
        /// </summary>
        /// <param name="traceClinch"></param>
        public void SaveClinchData(TraceClinch traceClinch)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceClinch)
                  .AS($"trace_clinch{HashUtils.GetHashAsInt(traceClinch.TraceId, 10)}")
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 存储FDS关键数据
        /// </summary>
        /// <param name="traceFDSKey"></param>
        public void FdsKetSave(List<TraceFDSKey> traceFDSKeys, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceFDSKeys).AS($"trace_fds_key{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand();

                Tools.ProduceLogText($"成功存储{traceFDSKeys.Count}条FDS关键数据，追溯码[{code}]");
            }
        }

        /// <summary>
        /// 存储FDS数据
        /// </summary>
        /// <param name="traceFDS"></param>
        public void FdsSave(List<TraceFDS> traceFdses, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceFdses).AS($"trace_fds{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand();

                Tools.ProduceLogText($"成功存储{traceFdses.Count}条FDS数据，追溯码[{code}]");
            }
        }

        /// <summary>
        /// 根据二维码与工位号查询是否存在出入站记录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool NgStationIsSave(string code, string station, string status)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<NgStation>().Any(x => x.TraceId == code && x.Station == station && x.Status == status);
            }
        }

        /// <summary>
        /// 是否存在数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public List<PartProcess> CodeIsSave(string code, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").Where(x => x.TraceId == code && x.Station == station).ToList();
            }
        }

        /// <summary>
        /// 根据工位号与二维码查询过点数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="lastStation"></param>
        public List<PartProcess> GetStationData(string code, List<string> stations)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").Where(x => x.TraceId == code && stations.Contains(x.Station)).ToList();
            }
        }

        /// <summary>
        /// 更新工位开始时间
        /// </summary>
        /// <param name="partProcess"></param>
        public void UpDateStationStartTime(PartProcess partProcess)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(partProcess.TraceId, 10)}").SetColumns(x => x.StartTime == partProcess.StartTime).Where(x => x.Id == partProcess.Id).ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入NG台出入站数据
        /// </summary>
        /// <param name="ngStation"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void NgStationSave(NgStation ngStation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                int count = db.Insertable(ngStation).ExecuteCommand();

                if (count > 0)
                {
                    string status = ngStation.Status.Equals("1") ? "出站" : "入站";

                    Tools.ProduceLogText($"成功记录一条[{status}]信息，追溯码[{ngStation.TraceId}]，{status}工位[{ngStation.Station}]");
                }
            }
        }

        /// <summary>
        /// 入站存储
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <param name="now"></param>
        public bool InsertStationStartTime(string code, string station, DateTime now, string operation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(new PartProcess()
                {
                    StartTime = now,
                    Station = station,
                    TraceId = code,
                    Operation = operation
                }).AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 插入OrderTrace
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool InsertOrderTrace(string orderId, string code, string lineName)
        {
            using (var db = SqlSugarConfig.Db)
            {
                bool isSave = db.Queryable<OrderTrace>().Any(x => x.OrderId == orderId && x.TraceId == code);

                if (!isSave)
                    return db.Insertable(new OrderTrace()
                    {
                        OrderId = orderId,
                        TraceId = code,
                        CreateTime = DateTime.Now,
                        Status1 = "0",
                        Status2 = "0",
                        Status3 = "0",
                        Status4 = "0",
                        LineName = lineName,
                    }).ExecuteCommand() > 0;

                return !isSave;
            }
        }

        /// <summary>
        /// 出站更新
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <param name="now"></param>
        /// <returns></returns>
        public bool UpdateStationEndTime(string code, string result, string station, DateTime now, string operation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                List<PartProcess> partProcesses = db.Queryable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").Where(x => x.TraceId == code && x.Station == station).ToList();

                if (partProcesses.Count == 0)
                {

                    if (InsertStationEndTime(code, station, now, result, operation))

                        Tools.ProduceLogTextError($"[{station}]触发出站存储，出站时间[{now}]，追溯码[{code}]");

                    return true;
                }
                else
                {
                    // 判断数据条目
                    if (partProcesses.Count == 1)
                    {
                        PartProcess partProcess = partProcesses.FirstOrDefault();

                        // 判断执行更新或插入
                        return UpDateOrInsertEndStation(partProcess, db, now, result, code, station, operation);
                    }
                    else
                    {
                        PartProcess partProcess = partProcesses.OrderByDescending(x => x.Id).FirstOrDefault();

                        // 判断执行更新或插入
                        return UpDateOrInsertEndStation(partProcess, db, now, result, code, station, operation);
                    }
                }
            }
        }

        /// <summary>
        /// 判断执行插入还是更新
        /// </summary>
        /// <param name="partProcess"></param>
        /// <param name="db"></param>
        /// <param name="now"></param>
        /// <param name="result"></param>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        private bool UpDateOrInsertEndStation(PartProcess partProcess, SqlSugarClient db, DateTime now, string result, string code, string station, string operation)
        {
            // 判断是否有结束时间，有则新插入，无则更新
            if (Tools.IsDateTimeValid(partProcess?.EndTime))
            {
                int v = db.Updateable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(partProcess.TraceId, 10)}")
                      .SetColumns(x => x.EndTime == now)
                      .SetColumns(x => x.Result == result)
                      .Where(x => x.Id == partProcess.Id)
                      .ExecuteCommand();

                Tools.ProduceLogText($"[{station}]触发出站更新，出站时间[{now}]，追溯码[{code}]");
                return true;
            }
            else
            {
                // 有结束时间，插入
                if (InsertStationEndTime(code, station, now, result, operation))

                    Tools.ProduceLogTextError($"[{station}]触发出站存储，出站时间[{now}]，追溯码[{code}]");

                return true;
            }
        }

        /// <summary>
        /// 出站存储
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <param name="now"></param>
        /// <returns></returns>
        private bool InsertStationEndTime(string code, string station, DateTime now, string result, string operation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(new PartProcess()
                {
                    StartTime = now.AddMinutes(-1),
                    EndTime = now,
                    Station = station,
                    TraceId = code,
                    Result = result,
                    Operation = operation,
                }).AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 更新产量
        /// </summary>
        /// <param name="orderId"></param>
        public void UpdateProduction(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<OrderStatus>().SetColumns(s => s.EndProduction == s.EndProduction + 1).Where(x => x.OrderId == orderId).ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入打码数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pointCode"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public int InsertPointCode(string code, string pointCode, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(new TracePoint()
                {
                    PointCode = pointCode,
                    Station = station,
                    TraceId = code,
                    CreateTime = DateTime.Now,
                    CodePushStatuses = "0"
                }).AS($"trace_point{HashUtils.GetHashAsInt(code, 10)}")
                .ExecuteCommand();
            }
        }

        /// <summary>
        /// 是否存储OrderTrace
        /// </summary>
        /// <param name="code"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool OrderTraceIsSave(string code, string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>().Any(x => x.TraceId == code && x.OrderId == orderId);
            }
        }

        /// <summary>
        /// 存储OrderTrace数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="orderId"></param>
        public void OrderTraceSave(string code, string orderId, DateTime now)
        {
            using (var db = SqlSugarConfig.Db)
            {
                if (!OrderTraceIsSave(code, orderId))

                    db.Insertable(new OrderTrace()
                    {
                        CreateTime = now,
                        OrderId = orderId,
                        TraceId = code,
                        Status1 = "0",
                        Status2 = "0",
                        Status3 = "0",
                        Status4 = "0",
                        LineName = "W04左右前纵梁"
                    }).ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入点检数据
        /// </summary>
        /// <param name="spotChack"></param>
        public int SpotChackSave(SpotChack spotChack)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(spotChack).ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据工单号查询工单
        /// </summary>
        /// <param name="x"></param>
        public OrderStatus QueryOrderByOrderId(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>().Where(x => x.OrderId == orderId).First();
            }
        }

        /// <summary>
        /// 根据工单改变工位推送状态
        /// </summary>
        /// <param name="orderId"></param>
        public void UpDateOrderTraceStatus2(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<OrderTrace>().SetColumns(x => x.Status2 == "1").Where(x => x.OrderId == orderId).ExecuteCommand();
            }
        }

        /// <summary>
        /// 追溯码查询过站信息
        /// </summary>
        /// <param name="traceId"></param>
        public List<PartProcess> GetProcessDataByTraceId(string traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(traceId, 10)}").Where(x => x.TraceId == traceId).ToList();
            }
        }

        /// <summary>
        /// 增补上个工位数据
        /// </summary>
        /// <param name="lastStation"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool LastStationDataIsSave(string lastStation, string code)
        {
            DateTime now = DateTime.Now;

            using (var db = SqlSugarConfig.Db)
            {
                return db.Insertable(new PartProcess()
                {
                    StartTime = now,
                    EndTime = now,
                    Station = lastStation,
                }).AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}")
                .ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 备份扫码校验记录
        /// </summary>
        /// <param name="code"></param>
        public void BackUpCode(List<string> codes, string station)
        {
            foreach (var code in codes)
            {
                try
                {
                    using (var db = SqlSugarConfig.Db)
                    {
                        int v = db.Insertable(new BackUpCode()
                        {
                            CreateTime = DateTime.Now,
                            TraceId = code,
                            Station = station
                        }).ExecuteCommand();

                        if (v > 0)
                        {
                            Tools.ProduceLogText($"[{station}]备份了一条校验数据，追溯码[{code}]");
                        }
                    }
                }
                catch (Exception e)
                {
                    Tools.ProduceLogTextError($"[{station}]校验备份失败，追溯码[{code}]，原因是{e.Message}");
                }
            }
        }

        /// <summary>
        /// 根据工位与追溯码查询数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="lastStation"></param>
        public List<PartProcess> GetProcessDataByTraceIdAndStation(string code, string lastStation)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").Where(x => x.TraceId == code && x.Station == lastStation).ToList();
            }
        }

        /// <summary>
        /// 根据主键更新数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool UpDateLastStationEndTimeById(int id, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Updateable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(code, 10)}").SetColumns(x => x.EndTime == DateTime.Now).Where(x => x.Id == id).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 数据是否存储
        /// </summary>
        /// <param name="traceId"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool ProcessDataFromCsvIsSave(string traceId, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PartProcess>().AS($"trace_process{HashUtils.GetHashAsInt(traceId, 10)}").Any(x => x.TraceId == traceId && x.Station == station);
            }
        }

        /// <summary>
        /// 数据存储
        /// </summary>
        /// <param name="traceRivete"></param>
        public PartProcess SaveProcessDataFromCsv(TraceRivete traceRivete, string result)
        {
            using (var db = SqlSugarConfig.Db)
            {
                PartProcess partProcess = new PartProcess()
                {
                    Station = traceRivete.Station,
                    TraceId = traceRivete.TraceId,
                    StartTime = DateTime.Parse(traceRivete.DataTime),
                    EndTime = DateTime.Parse(traceRivete.DataTime).AddMinutes(1),
                    Operation = MappingTable.GetOperationId(traceRivete.Station),
                    Result = result
                };

                db.Insertable(partProcess).AS($"trace_process{HashUtils.GetHashAsInt(traceRivete.TraceId, 10)}").ExecuteCommand();

                return partProcess;
            }
        }

        /// <summary>
        /// 数据存储
        /// </summary>
        /// <param name="traceClinch"></param>
        public PartProcess SaveProcessDataFromCsv(TraceClinch traceClinch, string result)
        {
            using (var db = SqlSugarConfig.Db)
            {
                PartProcess partProcess = new PartProcess()
                {
                    Station = traceClinch.Station,
                    TraceId = traceClinch.TraceId,
                    StartTime = DateTime.Parse(traceClinch.DataTime),
                    EndTime = DateTime.Parse(traceClinch.DataTime).AddMinutes(1),
                    Operation = MappingTable.GetOperationId(traceClinch.Station),
                    Result = result
                };

                db.Insertable(partProcess).AS($"trace_process{HashUtils.GetHashAsInt(traceClinch.TraceId, 10)}").ExecuteCommand();

                return partProcess;
            }
        }

        internal void SaveClinchCurve(TraceClinceCurve traceClinceCurve)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceClinceCurve).ExecuteCommand();
            }
        }

        /// <summary>
        /// 查出未推送的明暗码
        /// </summary>
        /// <param name="statuses"></param>
        /// <returns></returns>
        public List<TracePoint> QueryPoint(string status, int i)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TracePoint>().AS($"trace_point" + i).Where(x => x.CodePushStatuses != (status)).ToList();
            }
        }

        /// <summary>
        /// 改变明暗码推送状态
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdatePointSaveStatus(int id, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                int v = db.Updateable<TracePoint>().AS($"trace_point{HashUtils.GetHashAsInt(code, 10)}").SetColumns(x => x.CodePushStatuses == "1").Where(x => x.Id == id).ExecuteCommand();

                return v > 0;


            }

        }

        internal OrderTrace GetOrderCreatetime(string traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>().Where(x => x.TraceId == traceId).First();
            }
        }

        internal List<TraceFDS> GetFdsData(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceFDS>().AS($"trace_fds{HashUtils.GetHashAsInt(code, 10)}").Where(x => x.TraceId == code).ToList();
            }
        }

        internal List<TraceFDSKey> GetFdsKeyData(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceFDSKey>().AS($"trace_fds_key{HashUtils.GetHashAsInt(code, 10)}").Where(x => x.TraceId == code).ToList();
            }

        }

        /// <summary>
        /// 查询涂胶视觉数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public List<TraceGlueVision> GetGlueVisionData(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceGlueVision>()
                         .AS($"trace_glue_vision{HashUtils.GetHashAsInt(code, 10)}")
                         .Where(x => x.Trace_id == code)
                         .ToList();
            }
        }

        /// <summary>
        /// 查询弧焊视觉数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public List<TraceWeldVision> GetSpotWeldData(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceWeldVision>()
                         .AS($"trace_weld_vision{HashUtils.GetHashAsInt(code, 10)}")
                         .Where(x => x.TraceId == code)
                         .ToList();
            }
        }

        /// <summary>
        /// 更新状态2为完成状态
        /// </summary>
        /// <param name="orderTrace"></param>
        internal void UpdateStatus2(OrderTrace orderTrace)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<OrderTrace>().SetColumns(x => x.Status2 == "1").Where(x => x.Id == orderTrace.Id).ExecuteCommand();
            }
        }

        /// <summary>
        ///根据二维码查询绑定工单号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<OrderTrace> GetOrderIdFromOrderTrace(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>().Where(x => x.TraceId == code).ToList();
            }
        }

        internal List<OrderStatus> GetOrder(List<string> idList)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderStatus>().Where(x => idList.Contains(x.OrderId)).ToList();
            }
        }
    }
}


